package com.xneure.utils.formatfile.inifile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

public class IniFileParse{
	public static IniFileObject parse(String filePath){
		return parse(filePath,true);
	}

	public static IniFileObject parse(String filePath,boolean useSpace){
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		Resource resource = resolver.getResource(filePath);
		try{
			return parse(resource.getFile(),useSpace);
		}catch(IOException e){
			return null;
		}
	}

	public static IniFileObject parse(File file){
		return parse(file,true);
	}

	public static IniFileObject parse(File file,boolean useSpace){
		if(file.exists() == false){
			return null;
		}
		IniFileObject iniObject;
		BufferedReader reader = null;
		try{
			iniObject = new IniFileObject();
			String line;
			IniSection section = null;
			reader = new BufferedReader(new FileReader(file));
			while((line = reader.readLine()) != null){
				if(line.length() > 0){
					if(useSpace == false){
						line = line.trim();
					}
					if(line.startsWith(";")){
						continue;
					}
					if(line.startsWith("[") && line.endsWith("]")){
						section = new IniSection(line.substring(1,line.length() - 1));
						iniObject.addSection(section);
					}else{
						int index = line.indexOf("=");
						if(index != -1){
							String k = line.substring(0,index);
							String v = line.substring(index + 1,line.length());
							section.addValue(k,v);
						}
					}
				}
			}
			return iniObject;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			if(null != reader){
				try{
					reader.close();
				}catch(IOException e){
					e.printStackTrace();
				}
			}
		}
	}
}
